<?php
/**
 * Abstract Application Controller 
 *  
 * @package    Lazy Framework
 * @subpackage controller
 * @author     Eduardo Marcolino <eduardo.marcolino@gmail.com>
 * @copyright  (c) 2010 Eduardo Marcolino <eduardo.marcolino@gmail.com>
 */

abstract class Controller {
    public $template;
    public $attributes = array();
    
    abstract function index();
    
    /**
     * This method will be called before any method in the class
     * Use this to configure commons setting for all methods
     */
    public function preExecute(){}

    /**
     * @return WebRequest request
     */
	public function getRequest() {
		return Context::getInstance()->getRequest();
	}
	/**
	 * Shortcut to get a key in request parameter
	 * @param String $value
	 */
	public function getRequestParameter($key) {
		return Context::getInstance()->getRequest()->getParameter($key);
	}
    /**
     * Set an attribute to render in template
     * @param String attr
     * @param String value
     */
    public function setVar($attr, $value) {
      $this->attributes[$attr] = $value;
    }
    /**
     * Set a template to render
     * @param String template
     */
    public function setTemplate($template) {
      $this->template = $template;
    }
    /**
	 * @return Outlet instance
	 */
    public function getOutletInstance() {
      return Outlet::getInstance();
    }
    /**
     * Set flash messages that will be erased on the next request
     * @param $key
     * @param $value
     */
    public function setFlash($key,$value) {
    	Session::getInstance()->setFlash($key,$value);
    }
    
    public function dispatcher()
    {
    	ob_get_clean();
    	
    	$this->preExecute();
    	$action = Context::getInstance()->getActionName();
    	$this->$action();
    	
    	$twig = Context::getInstance()->getTemplate();
    	$template = $twig->loadTemplate($this->template);
    	
    	ob_get_clean();
    	
    	$app_attributes = 
			array(	'app_webcontent' => WEB_PATH,
          			'app_controller' => Context::getInstance()->getControllerName(),
		  			'app_action'     => Context::getInstance()->getActionName(),
	      			'flash'          => Session::getInstance()->getFlashMessages());
    	
    	echo $template->render(array_merge($app_attributes, $this->attributes));
    }
}
?>
